<?php


namespace App\Models\CacheModel\privatearea;


use App\Models\Api\BaseCache;
use think\Log;
use Exception;
use AstroTool\Cache\CacheManage;

class PrivateAreaUser extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_user';

    protected $cacheModel = 'privatearea.user';

    /**
     * 更新私域H5 用户信息
     * @param $privateAreaId
     * @param $map
     * @return int|string
     */
    public function SavaData($privateAreaId, $map)
    {
        try
        {
            $this->where(['id'=>$privateAreaId])->update($map);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $privateAreaId)->rmCache();
            return true;
        }
        catch (Exception $e)
        {
            Log::write('私域H5 PrivateAreaUser model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 缓存获取私域H5 用户信息
     * @param int $privateAreaId 用户ID
     * @param array $filed
     * @return array|bool|mixed
     * @throws Exception
     */
    public function getPrivateAreaInfo(int $privateAreaId, array $filed = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $privateAreaId)->getDataAndSet(function () use ($privateAreaId)
        {
            return $this->getPrivateAreaInfoFromDms($privateAreaId);
        }, $filed);

        return $data;
    }

    /**
     * 数据库获取私域H5 用户信息
     * @param int $privateAreaId
     * @return array|mixed
     */
    public function getPrivateAreaInfoFromDms(int $privateAreaId)
    {
        try
        {
            $data = $this->where(['id' => $privateAreaId])->field('id,uid,tel,token,token_expire')->findOrFail()->toArray();
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }
}
